package org.cuit.echo.seon.util;

import java.util.concurrent.*;

/**
 * @author SeonExlike
 * @since 2024/3/29
 */
public class BankWaterService {

    /**
     * 总共银行流水
     */
    private final static String SUM_OF_BANK_WATER = "sumOfBankWater";

    /**
     * 保存每个sheet计算出的银流结果
     */
    private final ConcurrentHashMap<String, Integer> sheetBankWaterMap = new ConcurrentHashMap<>();

    /**
     * 创建四个屏障，处理完之后执行barrierAction
     */
    private final CyclicBarrier barrier = new CyclicBarrier(4, () -> {
        int sumOfBankWater = sheetBankWaterMap.values().stream().mapToInt(e -> e).sum();
        sheetBankWaterMap.put(SUM_OF_BANK_WATER, sumOfBankWater);
        System.out.println(sheetBankWaterMap);
    });

    /**
     * 固定线程池
     */
    private final ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    /**
     * 计算金额
     */
    private void calculate() {
        // 模拟数据库中的数据
        int[] preparedData = new int[]{1, 2, 3, 4};
        for (int i = 0; i < 4; i++) {
            int finalI = i;
            threadPool.execute(() -> {
                // 模拟银行流水数据计算
                sheetBankWaterMap.put(Thread.currentThread().getName(), preparedData[finalI]);
                // 插入一个屏障
                try {
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        threadPool.shutdown();
    }

    public static void main(String[] args) {
        BankWaterService bankWaterService = new BankWaterService();
        bankWaterService.calculate();
    }
}
